const mqtt = require('mqtt');
const {
    v4: uuidv4
} = require('uuid');

const topics = ['temperature', 'humidity', "air"];
const broker = 'mqtt://127.0.0.1:1883';
const clientId = 'JavaScriptPublisher-' + uuidv4();
const username = 'admin';
const password = '123456';

const options = {
    clientId: clientId,
    username: username,
    password: password,
    clean: true
};

console.log('连接到服务器: ' + broker);
const client = mqtt.connect(broker, options);

let previousData = {
    temperature: 20, // 初始温度值，20摄氏度
    humidity: 70, // 初始湿度值，70%
    air: 50 // 初始空气质量值
};

client.on('connect', () => {
    console.log('已连接');

    topics.forEach((topic) => {
        setInterval(() => {
            publishSensorData(client, topic);
        }, 5 * 1000);
    });
});

function publishSensorData(client, topic) {
    const random = (Math.random() - 0.5) * 2; // 范围为 -1 到 1
    let lowerBound, upperBound, previousValue, maxDelta;

    switch (topic) {
        case 'temperature':
            lowerBound = 10;
            upperBound = 30;
            previousValue = previousData.temperature;
            maxDelta = 0.5; // 最大变化幅度为0.5度
            break;
        case 'humidity':
            lowerBound = 30;
            upperBound = 90;
            previousValue = previousData.humidity;
            maxDelta = 1.0; // 最大变化幅度为1%
            break;
        case 'air':
            lowerBound = 0;
            upperBound = 100;
            previousValue = previousData.air;
            maxDelta = 2.0; // 最大变化幅度为2
            break;
        default:
            return;
    }

    let data = previousValue + random * maxDelta;
    data = Math.max(lowerBound, Math.min(data, upperBound)); // 限制数据在合理范围内

    // 更新之前的数据
    previousData[topic] = data;

    // Convert the time to Beijing time
    const now = new Date();
    now.setHours(now.getHours() + 8); // Adjust to Beijing time by adding 8 hours
    const time = now.toISOString().replace('Z', '+08:00');

    const content = JSON.stringify({
        value: data,
        time: time
    });

    client.publish(topic, content, {
        qos: 2
    }, (err) => {
        if (err) {
            console.error('发布消息失败:', err);
        } else {
            console.log(`已发布消息到主题: ${topic} - 数据: ${content}`);
        }
    });
}

client.on('error', (err) => {
    console.error('连接错误:', err);
    client.end();
});

client.on('close', () => {
    console.log('连接已关闭');
});

client.on('reconnect', () => {
    console.log('尝试重新连接');
});

client.on('offline', () => {
    console.log('客户端离线');
});